﻿using System.Collections.Generic;
using System.Linq;
using Silent.MDB.Common.Data;
using Silent.MDB.Common.Services;

namespace Silent.MDB.Server.Model.Repositories
{
    public class FacultyRepository : IRepository<Faculty>
    {
        private readonly IDataContext m_dataContext;

        public FacultyRepository(IDataContext dataContext)
        {
            m_dataContext = dataContext;
        }

        public void Add(Faculty item)
        {
            m_dataContext.Faculties.Add(item);
        }

        public void Update(Faculty item)
        {
            var temp = m_dataContext.Faculties.FirstOrDefault(x => x.ObjectId == item.ObjectId);
            if (temp != null)
            {
                temp.Name = item.Name;
                temp.Dean = item.Dean;
                temp.DeaneryRoom = item.DeaneryRoom;
            }
        }

        public void Remove(Faculty item)
        {
            var temp = m_dataContext.Students.FirstOrDefault(x => x.ObjectId == item.ObjectId);
            if (temp != null)
            {
                m_dataContext.Students.Remove(temp);
            }
        }

        public ICollection<Faculty> Load(Faculty filter)
        {
            if (filter == null)
                return m_dataContext.Faculties.ToList();
            return m_dataContext.Faculties.Where(x => x.ParentObjectId == filter.ObjectId).ToList();
        }

        public void Save(ICollection<Faculty> data)
        {
            if (data != null)
            {
                foreach (var faculty in data)
                {
                    m_dataContext.Faculties.Add(faculty);
                }
            }
            m_dataContext.SaveChanges();
        }
    }
}
